/*
 * $Id: JsonRpcServiceView.java 50459 2007-03-28 21:25:32Z jdamick $
 *
 * Copyright 2006- Revolution Health Group.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Revolution Health Group.  (Confidential Information).
 * You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license 
 * agreement you entered into with Revolution Health Group.
 *
 */
package org.javason.jsonrpc;

import static org.javason.jsonrpc.JsonRpcConstants.ID;
import static org.javason.jsonrpc.JsonRpcConstants.MODEL_KEY;
import static org.javason.jsonrpc.JsonRpcConstants.RESPONSE_CONTENT_TYPE;

import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

import org.javason.jsonrpc.impl.JsonRpcResponse;
import org.javason.util.Metrics;

public class JsonRpcServiceView implements View {
	@SuppressWarnings("unchecked")
	public void render(Map resultMap, HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		
		Metrics timer = Metrics.beginCollection();
		
		response.setContentType(RESPONSE_CONTENT_TYPE);
		
		ServletOutputStream out = response.getOutputStream();
		
		Map<String, Object> responseMap = (Map<String, Object>) resultMap;
		Object model = responseMap.get(MODEL_KEY);
		
		JsonRpcResponse jsonResponse = new JsonRpcResponse(
				responseMap.get(ID), model, responseMap.get("error"));
	    
	    String jsonOutput = jsonResponse.toString();
	    
	    response.setContentLength(jsonOutput.length());
	    out.print(jsonOutput);
	
		out.flush();
		timer.endAndLogCollection();
	}
	
	public String getContentType() {
		return RESPONSE_CONTENT_TYPE;
	}
}
